package br.biofoco.p2p.rpc.torrent;

import java.io.File;
import java.util.ArrayList;

import org.apache.log4j.PropertyConfigurator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TorrentManager implements Runnable {

	private OptionTorrent ot = null;;
	private String[] data = null;
	private static Logger log = LoggerFactory.getLogger(TorrentManager.class);
	
	static{
		PropertyConfigurator
		.configure(System.getProperty("user.home") + File.separator
				+ "conf" + File.separator + "log4j.properties");
	}

	public TorrentManager(OptionTorrent ot, String ...data1 ) {
		data = data1;
		this.ot = ot;

	}

	public String execute() {

		String resposta = "";

		try {
			switch (ot) {

			case CREATE:
				
				ArrayList<String> al = new ArrayList<String>();
				for (String files : data) {
					log.debug("TorrentManager.executeOption() - Criar o arquivo torrent.");
					al.add(files);
				}
				CreateTorrent ct = new CreateTorrent(log);
				ct.createTorrentFile(al);
				resposta = "File(s) torrent created!!";
				break;

			case DOWNLOAD:
				log
						.debug("TorrentManager.executeOption() - Download do arquivo torrent.");
				DownloaderOfFiles dof = new DownloaderOfFiles(data, log);
				dof.executeDonwload();
				resposta = "Download efetuado!";
				break;

			case SERVER:
				
				log
						.debug("TorrentManager.executeOption() - Iniciar o servidor tracker.");
				ServerTorrentInitializer sti = new ServerTorrentInitializer(log);
				sti.initilizeServerTorrent();
				resposta = "Servidor iniciado!!";
				try {
					Thread.sleep(600000);
				} catch (InterruptedException e) {
					log
							.debug("TorrentManager.executeOption() - Erro na instancia do servidor."
									+ e.getMessage());
					e.printStackTrace();
				}
				break;

			case PUBLISH:
				
				log
						.debug("TorrentManager.executeOption() - Publicar o arquivo no tracker.");
				PublisherTracker pt = new PublisherTracker(log);
				pt.publish(data);
				resposta = "Torrent publicado no tracker.";
				break;

			default:
				
				log
						.debug("TorrentManager.executeOption() - Sem opcao para o processo de torrent.");
				resposta = "Opcao invalida!!!";
				break;
				
			}
		} catch (Exception e) {
			log
					.debug("TorrentManager.executeOption() - Erro na execucao da opcao = "
							+ e.getMessage());
			resposta = "Erro na execucao da opcao " + ot + ".";
		}

		return resposta;

	}
	
	@Override
	public void run() {
		try{
			execute();
			log.debug("TorrentManager.main(): Execucao do manager - encerrada.");
			}catch(Exception e){
				log.debug("TorrentManager.main(): Erro na execucao do teste - " + 
						e.getMessage());
				return;
			}		
	}

}
